package com.amumu.drama.portal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.category.dto.CategorySimpleDto;
import com.amumu.drama.common.modules.category.manager.CategoryManager;
import com.amumu.drama.common.modules.invitation.service.InvitationService;
import com.amumu.drama.common.modules.product.dao.PortalProductDao;
import com.amumu.drama.mapper.*;
import com.amumu.drama.model.*;
import com.amumu.drama.portal.domain.PmsPortalProductDetail;
import com.amumu.drama.portal.domain.PmsProductCategoryNode;
import com.amumu.drama.portal.service.PmsPortalProductService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service实现类
 * Created by macro on 2020/4/6.
 */
@Slf4j
@Service
public class PmsPortalProductServiceImpl implements PmsPortalProductService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PmsPortalProductServiceImpl.class);
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private PmsBrandMapper brandMapper;
    @Autowired
    private PmsProductAttributeMapper productAttributeMapper;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PortalProductDao portalProductDao;

    @Autowired
    private InvitationService invitationService;

    @Autowired
    private CategoryManager categoryManager;

    @Autowired
    private PmsProductTemplateMapper pmsProductTemplateMapper;

    @Override
    public List<PmsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize, Integer sort) {
        PageHelper.startPage(pageNum, pageSize);
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        criteria.andPublishStatusEqualTo(1);
        if (StrUtil.isNotEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
        }
        if (brandId != null) {
            criteria.andBrandIdEqualTo(brandId);
        }
        if (productCategoryId != null) {
            criteria.andProductCategoryIdEqualTo(productCategoryId);
        }
        //1->按新品；2->按销量；3->价格从低到高；4->价格从高到低
        if (sort == 1) {
            example.setOrderByClause("id desc");
        } else if (sort == 2) {
            example.setOrderByClause("sale desc");
        } else if (sort == 3) {
            example.setOrderByClause("price asc");
        } else if (sort == 4) {
            example.setOrderByClause("price desc");
        }
        return productMapper.selectByExample(example);
    }

    @Override
    public List<PmsProduct> list() {
        PmsProductExample example = new PmsProductExample();
        try {
            return productMapper.selectByExample(example);
        } catch (Exception e) {
            LOGGER.error("item list error", e);
        }
        return Collections.emptyList();
    }

    @Override
    public List<PmsProductCategoryNode> categoryTreeList() {
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        List<PmsProductCategory> allList = productCategoryMapper.selectByExample(example);
        List<PmsProductCategoryNode> result = allList.stream()
                .filter(item -> item.getParentId().equals(0L))
                .map(item -> covert(item, allList))
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public PmsPortalProductDetail detail(Long id, String invitationCode) {
        PmsPortalProductDetail result = new PmsPortalProductDetail();
        //获取商品信息
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        criteria.andProductCategoryIdEqualTo(id);
        List<PmsProduct> products = productMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(products)) {
            log.error("获取商品详情，商品不存在，id:{}", id);
            Asserts.fail("商品不存在:" + id);
        }
        PmsProduct product = products.get(0);
        result.setProduct(product);
        //获取品牌信息
        PmsProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(id);
        result.setProductCategory(productCategory);
        //直充商品模板
        List<PmsProductTemplate> pmsProductTemplates = pmsProductTemplateMapper.selectList(new LambdaQueryWrapper<PmsProductTemplate>()
                .eq(PmsProductTemplate::getProductCategoryId, product.getProductCategoryId()));
        if (CollectionUtil.isNotEmpty(pmsProductTemplates)) {
            result.setProductTemplate(pmsProductTemplates.get(0));
        }

        //获取商品属性信息
        PmsProductAttributeExample attributeExample = new PmsProductAttributeExample();
        attributeExample.createCriteria().andProductAttributeCategoryIdEqualTo(product.getProductAttributeCategoryId());
        List<PmsProductAttribute> productAttributeList = productAttributeMapper.selectByExample(attributeExample);
        result.setProductAttributeList(productAttributeList);
        //获取商品SKU库存信息
        BigDecimal invitationDiscount = invitationService.queryInvitationDiscount(invitationCode);
        LambdaQueryWrapper<PmsSkuStock> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PmsSkuStock::getProductId, product.getId());
        List<PmsSkuStock> skuStockList = skuStockMapper.selectList(wrapper);
        if (skuStockList != null && !skuStockList.isEmpty()) {
            skuStockList.forEach(e -> {
                e.setPromotionPrice(e.getPrice().multiply(invitationDiscount));
            });
            result.setSkuStockList(skuStockList);
        }
        return result;
    }

    @Override
    public List<CategorySimpleDto> listProductCategory() {
        return categoryManager.listProductCategory();
    }


    /**
     * 初始对象转化为节点对象
     */
    private PmsProductCategoryNode covert(PmsProductCategory item, List<PmsProductCategory> allList) {
        PmsProductCategoryNode node = new PmsProductCategoryNode();
        BeanUtils.copyProperties(item, node);
        List<PmsProductCategoryNode> children = allList.stream()
                .filter(subItem -> subItem.getParentId().equals(item.getId()))
                .map(subItem -> covert(subItem, allList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
